package com.igeek.addTwoNumbers;

/**
 * @Author: zhiyu
 * @Date:19:09
 * @DESC:
 */
public class ListNodeTest {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2,new ListNode(4,new ListNode(3)));
        ListNode l2 = new ListNode(5,new ListNode(6,new ListNode(4)));
//        ListNode l1 = new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9))));
//        ListNode l2 = new ListNode(9,new ListNode(9));
        ListNode listNode = addTwoNumbers(l1, l2);
        System.out.println("listNode = " + listNode);
        while (listNode!=null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode current = head;
        int carry = 0; //carry为进位值
        // 遍历两个链表，直到两个链表都为空，并且没有进位
        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            // 如果 l1 不为空，添加 l1 节点的值
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            // 如果 l2 不为空，添加 l2 节点的值
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            // 计算当前位的值和进位
            carry = sum / 10;
            current.next = new ListNode(sum % 10);
            current = current.next;
        }
        return head.next; //以案例为例,最终的结果链表是最终链表为0->5->7->9,返回时去掉头节点0,结果为5->7->9
    }
}
